<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 1.普通函数调用
      // function foo() {
      //   console.log('foo函数被调用了')
      // }
      // foo()

      // 2.生成器函数的定义
      // 默认返回: Generator
      function* foo() {
        console.log('111')
        yield 'hello'
        console.log('222')
        yield 'world'
        console.log('333')
        yield 'jane'
        console.log('444')
      }
      // iterator: 迭代器
      const result = foo()
      console.log(result)

      // 3.使用迭代器
      // 调用next,就会消耗一次迭代器
      // const res1 = result.next()
      // console.log(res1)
      // const res2 = result.next()
      // console.log(res2)
      // const res3 = result.next()
      // console.log(res3)
      // const res4 = result.next()
      // console.log(res4)

      // 4.生成器函数的执行顺序

      // 5.练习: 定义一个生成器函数, 依次可以生成1~10的数字
      function* bar() {
        for (let i = 1; i <= 10; i++) {
          yield i
        }
      }
      // const numIt = bar()
      // console.log(numIt.next())

      // 6.Generator和Promise一起来使用
      function* bar() {
        console.log('111')
        const result = yield new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve('hello world')
          }, 3000)
        })
        console.log(result)
      }

      const it = bar()
      it.next().value.then(value => {
        it.next(value)
      })
    </script>
  </body>
</html>
